package kugou

import (
	"api-go/cache"
	"api-go/serializer"
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/go-redis/redis/v8"
)

type Banner struct {
}

var ctx = context.Background()

//获取首页轮播图(通过爬虫)
func (service *Banner) Banner() *serializer.Response {
	//定义redis key和判断redis是否有该值
	redisKey := "kugou-banner"
	redisResult, err := cache.RedisClient.Get(ctx, redisKey).Result()
	//若redis没有该值则执行获取
	if err == redis.Nil {
		out := []map[string]interface{}{}
		url := "https://www.kugou.com"
		res, err := http.Get(url)
		if err != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		defer res.Body.Close()
		if res.StatusCode != 200 {
			fmt.Printf("status code error: %s\n", res.Status)
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		g, e := goquery.NewDocumentFromReader(res.Body)

		if e != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
		c := g.Find(".sliderItem")
		c.Each(func(i int, content *goquery.Selection) {
			//获取标题
			a, _ := content.Find("a").Attr("title")
			//获取地址
			b, _ := content.Find("a").Attr("href")
			//获取图片
			c, _ := content.Attr("data-bg")

			arr := map[string]interface{}{
				"title": a,
				"url":   b,
				"img":   c,
			}
			out = append(out, arr)

		})

		//将结果转为Json数据
		b, err := json.Marshal(out)
		if err != nil {
			fmt.Println(err)
		}
		//转为string存入redis
		err = cache.RedisClient.Set(ctx, redisKey, string(b), 24*time.Hour).Err()
		if err != nil {
			fmt.Println("err1", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}

		return serializer.OkResponse(out)
	} else if err != nil {
		fmt.Println("err2", err)
		return serializer.ErrorResponse(serializer.RedisError)
	} else {
		//将从redis获取的结果（string类型）转为map[string]inerface{}
		bodyMapData := []map[string]interface{}{}
		err = json.Unmarshal([]byte(redisResult), &bodyMapData)
		if err != nil {
			fmt.Println("err3", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}
		return serializer.OkResponse(bodyMapData)
	}

}
